#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#define PORT 8080
#define MAX_CLIENTS 30
#define BUF_SIZE 1024

int main() {
    int server_fd, client_fd, new_socket;
    struct sockaddr_in address;
    int opt = 1;
    int addrlen = sizeof(address);
    char buffer[BUF_SIZE] = {0};
    fd_set readfds;
    int max_sd;

    // 创建 socket
    if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
        perror("socket failed");
        exit(EXIT_FAILURE);
    }

    // 设置 socket 选项
    if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))) {
        perror("setsockopt");
        exit(EXIT_FAILURE);
    }

    address.sin_family = AF_INET;
    address.sin_addr.s_addr = INADDR_ANY;
    address.sin_port = htons(PORT);

    // 绑定 socket
    if (bind(server_fd, (struct sockaddr *) &address, sizeof(address)) < 0) {
        perror("bind failed");
        exit(EXIT_FAILURE);
    }

    // 监听 socket
    if (listen(server_fd, 3) < 0) {
        perror("listen");
        exit(EXIT_FAILURE);
    }

    // 清空 socket 集合
    FD_ZERO(&readfds);

    // 将服务器 socket 加入集合
    FD_SET(server_fd, &readfds);

    // 记录最大的文件描述符
    max_sd = server_fd;

    printf("Server listening on port %d\n", PORT);

    // 等待连接和数据
    while (1) {
        // 复制文件描述符集合
        fd_set temp_set = readfds;

        // 等待某个 socket 活动
        int activity = select(max_sd + 1, &temp_set, NULL, NULL, NULL);

        if ((activity < 0)) {
            perror("select error");
        }

        // 新连接
        if (FD_ISSET(server_fd, &temp_set)) {
            if ((new_socket = accept(server_fd, (struct sockaddr *) &address, (socklen_t * ) & addrlen)) < 0) {
                perror("accept");
                exit(EXIT_FAILURE);
            }

            // 将新的 socket 加入集合
            FD_SET(new_socket, &readfds);
            if (new_socket > max_sd) {
                max_sd = new_socket;
            }

            printf("New connection, socket fd is %d, ip is : %s, port : %d\n", new_socket, inet_ntoa(address.sin_addr),
                   ntohs(address.sin_port));
        }

        // 处理所有客户端 socket
        for (int i = 0; i <= max_sd; i++) {
            if (FD_ISSET(i, &temp_set)) {
                if (i == server_fd) {
                    continue;
                }

                // 读取数据
                int read_size = read(i, buffer, BUF_SIZE * sizeof(char));
                if (read_size > 0) {
                    printf("Client [%d]: %s\n", i, buffer);
                    memset(buffer, 0, BUF_SIZE);
                    send(i, buffer, strlen(buffer), 0);
                } else if (read_size == 0) {
                    // 客户端断开连接
                    puts("Client disconnected");
                    close(i);
                    FD_CLR(i, &readfds);
                } else {
                    perror("recv failed");
                    exit(EXIT_FAILURE);
                }
            }
        }
    }

    return 0;
}